<template>
   <!-- 弹窗组件 -->
   <div class="dialog-box">
      <el-dialog v-model="dialogVisible" :title="orderId ? '编辑采购单' : '新增采购单'" width="900">
         <el-form :model="form" label-width="100px">
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item label="采购负责人" required>
                     <el-input :disabled="isDetails" v-model="orderDetail.manager_name" placeholder="请选择"
                        suffix-icon="MoreFilled" @focus="openPurchasingDirectorPopup" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="负责人电话" required type="number">
                     <el-input :disabled="isDetails" v-model="orderDetail.manager_phone" placeholder="请输入" type="text"
                        maxlength="11" oninput="value=value.replace(/[^\d]/g,'')" />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item label="采购日期" required>
                     <el-date-picker :disabled="isDetails" v-model="orderDetail.purchase_date" type="date"
                        placeholder="请选择" />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-form-item label="备注">
               <el-input :disabled="isDetails" v-model="orderDetail.note" :placeholder="orderId ? '暂无备注' : '请输入'" />
            </el-form-item>

            <div class="supply-products">
               <div class="title">
                  <div class="title-text">
                     <div class="line"></div>
                     采购产品
                  </div>
                  <el-badge :value="orderDetail?.purchase_order_item?.length" class="item">
                     <el-button v-if="!isDetails" @click="openSelectProductsPopup">
                        选择产品
                     </el-button>
                  </el-badge>
               </div>
               <el-table border :data="orderDetail?.purchase_order_item" style="width: 100%">
                  <el-table-column prop="product_name" label="产品名称" width="100">
                     <template #default="scope">
                        <span>{{ scope.row.product_name ? scope.row.product_name : scope.row.spu_name }}</span>
                     </template>
                  </el-table-column>
                  <el-table-column prop="specification" label="规格型号" width="100">
                     <template #default="scope">{{ scope.row.unit_num + scope.row.specification }}</template>
                  </el-table-column>
                  <el-table-column prop="measure_unit_name" label="采购单位" width="100" />
                  <el-table-column prop="num" label="采购数量" width="130">
                     <template #default="scope">
                        <el-input :disabled="isDetails" v-model="scope.row.num" placeholder="请输入" type="number" min="0"
                           @input="(value) => handleInputChange(value, scope.row, 'num')" />
                     </template>
                  </el-table-column>
                  <el-table-column prop="price" label="采购单价(元)" width="150">
                     <template #default="scope">
                        <el-input disabled v-model="scope.row.price" placeholder="请输入" type="number" min="0"
                           @input="(value) => handleInputChange(value, scope.row, 'price')" />
                     </template>
                  </el-table-column>
                  <el-table-column prop="supplier_name" label="供应商" width="100">
                  </el-table-column>
                  <el-table-column prop="spu_measure_name" label="拆零" width="100">
                  </el-table-column>
                  <el-table-column prop="total_price" label="最终成交价(元)" width="100">
                     <template #default="scope">
                        {{ calculateItemTotal(scope.row) }}
                     </template>
                  </el-table-column>
                  <el-table-column label="操作" fixed="right" width="100">
                     <template #default="scope">
                        <el-button :disabled="isDetails" @click="handleRemoveProduct((scope.row as ProcurementItem).id)"
                           type="danger" link>移除</el-button>
                     </template>
                  </el-table-column>
               </el-table>
            </div>
            <div class="supply-products">
               <div class="title">
                  <div class="title-text">
                     <div class="line"></div>
                     价格设置
                  </div>
               </div>
               <el-row :gutter="20">
                  <el-col :span="12">
                     <el-form-item label="整单折扣(%)" type="number">
                        <el-input :disabled="isDetails" @input="(value) => handleOrderDiscountChange(value)"
                           type="number" v-model="orderDetail.order_discount" placeholder="请输入" min="0" max="100" />
                     </el-form-item>
                  </el-col>
                  <el-col :span="12">
                     <el-form-item label="整单成交额(元)">
                        <el-input v-model="orderDetail.total_amount" placeholder="请输入" disabled />
                     </el-form-item>
                  </el-col>
               </el-row>
            </div>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button @click="dialogVisible = false">取消</el-button>
               <el-button color="#626aef" v-if="!isDetails" @click="handleSubmit">
                  确定
               </el-button>
            </div>
         </template>
      </el-dialog>
      <!-- 选择供应商 -->
      <SelectSuppliers ref="selectSuppliersRef" @selectSupplier="handleSelectSupplier" />
      <!-- 选择采购负责人 -->
      <SelectPurchasingDirector ref="selectPurchasingDirectorRef"
         @selectPurchasingDirector="handleSelectPurchasingDirector" />
      <!-- 选择产品 -->
      <SelectProducts ref="selectProductsRef" @selectProducts="handleSelectProducts"
         :purchaseOrder-item="orderDetail.purchase_order_item" :supplier-id="Number(orderDetail.supplier_id)" />
   </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, defineEmits } from "vue";
import { ElMessage } from "element-plus";
import SelectSuppliers from "./SelectSuppliers.vue";
import SelectPurchasingDirector from "./SelectPurchasingDirector.vue";
import SelectProducts from "./SelectProducts.vue";
import { ProcurementDetail, ProcurementItem } from "../procurementType.ts";
import api from "@/api/index.js";
import dayjs from "dayjs";
const selectSuppliersRef = ref<any>(null); // 选择供应商弹窗
const selectPurchasingDirectorRef = ref<any>(null); // 选择采购负责人弹窗
const selectProductsRef = ref<any>(null); // 选择产品弹窗
const dialogVisible = ref<boolean>(false); // 弹窗控制器
const emit = defineEmits(["refreshList"]);
const form = reactive<any>({
   supplier_name: "",
   manager_name: "",
   manager_phone: "",
   purchase_date: "",
   remark: "",
});
// 订单详情
const orderDetail = ref<ProcurementDetail>({
   id: 0, // 订单id
   order_no: "", // 订单编号
   total_amount: 0,
   purchase_date: new Date(),
   create_time: "",
   supplier_id: "", // 供应商id
   supplier_name: "", // 供应商名称
   manager_member_id: 0, // 采购负责人id
   manager_name: "", // 采购负责人名称
   manager_phone: 0, // 采购负责人电话
   status: 0, // 状态
   pur_state: 0, // 采购状态
   note: "", // 备注
   creator_name: "", // 创建人
   audit_name: "", // 审核人
   audit_note: "", // 审核备注
   audited_at: new Date(), // 审核时间
   created_at: new Date(), // 创建时间
   status_note: "", // 状态备注
   order_discount: 100, // 整单折扣
   specification: "", // 规格型号
   total_price: 0, // 整单成交额
   purchase_order_item: [],
});
const orderId = ref<number>();
// 获取订单详情
const getOrderDetail = async (id: number) => {
   const res = await api.procurement.purchaseOrderDetail({ id: id });
   if (res.code == 200) {
      orderDetail.value = res.data;
   }
};
const isDetails = ref<boolean>(false);
const openLoading = (id?: number, isDetail?: boolean) => {
   dialogVisible.value = true;
   orderId.value = id;
   isDetails.value = isDetail || false;
   if (id) {
      getOrderDetail(id);
   } else {
      orderDetail.value = {
         order_discount: 100, // 整单折扣
         purchase_order_item: [],
      } as unknown as ProcurementDetail;
   }
};
// 选择供应商
const openSelectSuppliersPopup = (e: any) => {
   selectSuppliersRef.value.openLoading();
   e.target.blur();
};

// 选择采购负责人
const openPurchasingDirectorPopup = (e: any) => {
   selectPurchasingDirectorRef.value.openLoading();
   e.target.blur();
};
// 选择产品
const openSelectProductsPopup = (e: any) => {
   // if (!orderDetail.value.supplier_id) {
   //    ElMessage.warning("请先选择供应商");
   //    return;
   // }
   selectProductsRef.value.openLoading();
};
interface PurchaseGoods {
   no: string;
   num: number;
   unit_price: number;
   discount: number;
}
interface PurchaseOrderParams {
   supplier_id: number;
   manager_member_id: number;
   purchase_date: string;
   note: string;
   purchase_goods: PurchaseGoods[];
   order_discount: number;
}

// 创建采购订单
const createPurchaseOrder = async (params: PurchaseOrderParams) => {
   const res = await api.procurement.purchaseOrderCreate(params);
   if (res.code == 200) {
      ElMessage.success("创建成功");
   }
};

// 更新采购订单
const updatePurchaseOrder = async (params: PurchaseOrderParams) => {
   const res = await api.procurement.purchaseOrderUpdate({ ...params, id: orderId.value });
   if (res.code == 200) {
      ElMessage.success("更新成功");
   }
};

const handleSubmit = async () => {
   let goodsList = orderDetail.value.purchase_order_item.map((item) => ({
      no: item.product_no,
      num: Number(item.num),
      unit_price: Number(item.price),
      discount: Number(item.discount),
   }));

   // 格式化日期为 YYYY-MM-DD                                                                                                                                                                                                                                                                                                                                           
   const formattedDate = orderDetail.value.purchase_date ? dayjs(orderDetail.value.purchase_date).format("YYYY-MM-DD") : "";
   const params: PurchaseOrderParams = {
      supplier_id: Number(orderDetail.value.supplier_id),                
      manager_member_id: orderDetail.value.manager_member_id,
      purchase_date: formattedDate,
      note: orderDetail.value.note,
      purchase_goods: goodsList,
      order_discount: Number(orderDetail.value.order_discount),
   };
   // 验证日期是否选择
   if (!formattedDate) {
      ElMessage.warning("请选择采购日期");
      return;
   }

   if (orderId.value) {
      await updatePurchaseOrder(params);
      // 刷新列表
      emit("refreshList");
   } else {
      await createPurchaseOrder(params);

      // 刷新列表
      emit("refreshList");
   }
   dialogVisible.value = false;
};

interface Supplier {
   Sname: string;
   name: string;
   Sphone: string;
   Sposition: string;
   id: number;
}

// 处理选择供应商
const handleSelectSupplier = (supplier: Supplier) => {
   orderDetail.value.supplier_name = supplier.Sname; // 供应商名称
   orderDetail.value.supplier_id = supplier.id.toString(); // 供应商id
};

// 处理选择采购负责人
const handleSelectPurchasingDirector = (purchasingDirector: any) => {
   orderDetail.value.manager_name = purchasingDirector.name; // 采购负责人名称
   orderDetail.value.manager_member_id = purchasingDirector.id; // 采购负责人id
   orderDetail.value.manager_phone = purchasingDirector.mobile; // 采购负责人电话
};
// 处理选择产品
const handleSelectProducts = (products: any) => {
   console.log(products, "products");

   // 直接替换为新选择的产品，而不是累加
   let newProducts = products.map((item: any) => ({
      id: item.id, // 产品id（用于表格行的唯一标识）
      product_id: item.id, // 产品id（用于与SelectProducts组件的数据匹配）
      spu_name: item.name, // 产品名称
      specification: item.specification, // 规格型号
      price: Number(Number(item.price).toFixed(2)), // 采购单价
      num: 1, // 采购数量
      supplier_name: item.suppliers.map((item: any) => item.name), // 供应商
      spu_measure_unit_name: item.open_unit_name, // 单位
      spu_measure_name: item.spu_measure_unit_name, // 拆零
      product_no: item.no, // 产品编码
      measure_unit_name: item.measure_unit_name, // 采购单位单位
      unit_num: item.unit_num,
   }));

   // 直接替换整个产品列表，而不是累加
   orderDetail.value.purchase_order_item = newProducts;

   console.log('更新后的产品列表:', orderDetail.value.purchase_order_item);

   // 添加产品后立即计算总金额
   calculateTotalAmount();
};
// 移除产品
const handleRemoveProduct = (id: number) => {
   console.log(id);
   orderDetail.value.purchase_order_item = orderDetail.value.purchase_order_item.filter((item: ProcurementItem) => item.id !== id);
};
interface PurchaseOrderItem {
   spu_name: string;
   specification: string;
   unit: string;
   num: number;
   unit_price: number;
   discount: number;
   discount_price: number;
   final_price: number;
}

// 格式化数字为两位小数
const formatNumber = (num: number): number => {
   return Math.max(0, Number(num.toFixed(2)));
};

// 验证输入是否为正数
const validatePositiveNumber = (value: string | number): number => {
   const num = Number(value);
   return num < 0 ? 0 : num;
};

// 计算单个产品的总价
const calculateItemTotal = (item: any): string => {
   const price = Number(item.price) || 0;
   const num = Number(item.num) || 0;
   return (price * num).toFixed(2);
};

// 计算整单成交额
const calculateTotalAmount = () => {
   if (!orderDetail.value.purchase_order_item?.length) {
      orderDetail.value.total_amount = 0;
      return;
   }

   // 计算所有产品的最终成交价总和
   const totalBeforeDiscount = orderDetail.value.purchase_order_item.reduce((sum, item) => {
      const price = Number(item.price) || 0;
      const num = Number(item.num) || 0;
      return sum + price * num;
   }, 0);

   // 应用整单折扣
   const orderDiscount = validatePositiveNumber(orderDetail.value.order_discount || 100);
   orderDetail.value.total_amount = formatNumber(totalBeforeDiscount * (orderDiscount / 100));
};

// 监听产品列表变化
watch(
   () => orderDetail.value.purchase_order_item,
   () => {
      calculateTotalAmount();
   },
   { deep: true }
);

// 监听整单折扣变化
watch(
   () => orderDetail.value.order_discount,
   () => {
      calculateTotalAmount();
   }
);

// 处理输入值变化
const handleInputChange = (value: string, row: any, field: string) => {
   if (value === "") {
      row[field] = 0;
      return;
   }

   let num = Number(value);

   // 确保数值不小于0
   if (num < 0) {
      num = 0;
   }

   // 如果是折扣，确保不超过100
   if (field === "discount" && num > 100) {
      num = 100;
   }

   // 限制小数位数不超过4位
   const decimalPlaces = (num.toString().split(".")[1] || "").length;
   if (decimalPlaces > 4) {
      num = Number(num.toFixed(4));
   }

   row[field] = num;
};

// 处理整单折扣变化
const handleOrderDiscountChange = (value: string) => {
   if (value === "") {
      orderDetail.value.order_discount = 0;
      return;
   }

   let num = Number(value);

   // 确保数值在0-100之间
   if (num < 0) {
      num = 0;
   } else if (num > 100) {
      num = 100;
   }

   orderDetail.value.order_discount = num;
   // 触发重新计算总金额
   calculateTotalAmount();
};

defineExpose({
   openLoading,
});
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
   --el-dialog-padding-primary: 0px;
}

::v-deep .el-dialog__header {
   padding: 10px 16px;
   border-bottom: 1px solid #f0f0f0;
   font-weight: bold;
}

::v-deep .dialog-footer {
   padding: 10px 16px;
   border-top: 1px solid #f0f0f0;
}

::v-deep .el-dialog__headerbtn .el-dialog__close {
   color: #000;
}

::v-deep .el-dialog__body {
   padding: 10px 10px;
}

:deep(.el-form-item__label) {
   justify-content: flex-start;
}

:deep(.el-form-item) {
   flex-direction: column;
   margin-bottom: 7px;
}

:deep(.el-select__wrapper) {
   background: #fafcfb;
}

:deep(.el-badge__content.is-fixed) {
   color: #666;
   border-radius: 3px;
   padding: 4px;
}

:deep(.el-table .cell) {
   display: flex;
   justify-content: center;
}

:deep(.el-button:hover) {
   color: #6860ff;
   background: #f4f5f7;
}

:deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
   width: 100%;
}

:deep(.el-input__wrapper:hover) {
   box-shadow: inset 0 0 0 1px #6860ff;
}

.supply-products {
   margin-top: 20px;

   .title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10px;
      font-weight: bold;

      .title-text {
         display: flex;
         align-items: center;

         .line {
            height: 17px;
            width: 2px;
            border-radius: 12px;
            margin-right: 8px;
            background-color: #6860ff;
         }
      }
   }
}

.image-list {
   display: flex;
   gap: 8px;

   .el-image {
      width: 40px;
      height: 40px;
      border-radius: 4px;
   }
}
</style>
